package org.fly.service.impl;

import org.apache.commons.lang.StringUtils;
import org.fly.bean.User;
import org.fly.bean.common.BusinessException;
import org.fly.contants.ErrorConstant;
import org.fly.contants.WebConstant;
import org.fly.dao.UserDao;
import org.fly.service.UserService;
import org.fly.utils.CacheUtil;
import org.fly.utils.StrGenerator;
import org.fly.utils.UUIDFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fly
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    UserDao userDao;

    @Override
    public User login(String account, String password) throws BusinessException {
        User user = userDao.findByAccount(account);
        if(user == null ){
            throw new BusinessException(ErrorConstant.code_login_no_user, ErrorConstant.msg_login_no_user);
        }
        if(!user.getPassword().equals(password)){
            throw new BusinessException(ErrorConstant.code_login_password_error, ErrorConstant.msg_login_password_error);
        }
        fillCookieMap(user);
        CacheUtil.cache(user.getCookieMap().get(WebConstant.cookie_token),user);
        return user;
    }

    @Override
    public void logout(String token) {
        CacheUtil.remove(token);
    }

    @Override
    public void save(User bean) {
        if(StringUtils.isNotBlank(bean.getId())){
            userDao.update(bean);
        }else {
            bean.setId(UUIDFactory.random());
            bean.setCreateTime(System.currentTimeMillis());
            userDao.insert(bean);
        }
    }

    @Override
    public User getUserByToken(String token){
        if(StringUtils.isBlank(token)){
            return null;
        }
        User user = CacheUtil.getByKey(token);
        return user;
    }
    @Override
    public void updatePassword(String id, String oldPassword, String newPassword) throws BusinessException {
        User user = userDao.findById(id);
        if(!user.getPassword().equals(oldPassword)){
            throw new BusinessException(ErrorConstant.code_login_password_error, ErrorConstant.msg_login_password_error);
        }
        user.setPassword(newPassword);
        userDao.update(user);
    }
    private void fillCookieMap(User user){
        Map<String,String> cookieMap = new HashMap<>();
        cookieMap.put(WebConstant.cookie_fake, StrGenerator.generateRandomStr(32));
        cookieMap.put(WebConstant.cookie_name,StrGenerator.EncoderByMd5(user.getAccount()));
        cookieMap.put(WebConstant.cookie_token,StrGenerator.EncoderByMd5(user.getAccount()+"_"+user.getSalt()));
        user.setCookieMap(cookieMap);
    }
}
